<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/31
 * Time: 上午9:12
 */

namespace app\common\controller;


use app\common\model\Agent;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGive;
use app\common\model\CardMember;
use app\common\model\CardPaycard;
use app\common\model\CardUserGet;
use app\common\model\Merchant;
use app\common\model\MerchantCashier;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Controller;
use think\config;


use Wechat\Wxobjopen;

class TemplateMsgt extends Controller
{


    public function send_tpl($type,$data)
    {
//        $Acton = new ActionLogs();
//        $Acton->writelog("payos","templatemsgt","send_tpl","1:",$data);
//        $Acton->writelog("payos","templatemsgt","send_tpl","1-0:",$type);
       switch ($type){
//           case "pay_tz":
//               $data['tpl_type'] = 'pay_tpl';
//               $data['template_id'] = $this->get_tpl_id($data);
//               $res = $this->pay_msg_tomach_ser($data);
//               break;
           case "pay_count":
               $data['tpl_type'] = 'pre_man_tpl';
               $data['template_id'] = $this->get_tpl_id($data);
               $res = $this->pay_count_tomach($data);
               break;
           case "pay_balance":
               $data['tpl_type'] = 'card_ye_tpl';
               $data['template_id'] = $this->get_tpl_id($data);
               $res = $this->balance_change_touser($data);
               break;
           case "put_gift":
               $data['tpl_type'] = 'card_zs_tpl';
               $data['template_id'] = $this->get_tpl_id($data);
               $res = $this->gift_put_touser($data);
               break;
           default:
               $res = '';
               break;
       }
       return $res;
    }

    //支付通知  向商家  服务商发送
    private function pay_msg_tomach_ser($id,$orderid){
        $map['pre_tpl'] = '';
        $map['id'] = $id;
        $System = new System();
        $Wxopen = new WxOpen();
        $Merchant = new Merchant();
        $Agent=new Agent();
        $mach = $Merchant->where($map)->find();
        $agentinfo=$Agent->where(['id'=>$mach['agent']])->find();
        $config = $System->where(array('id' => 1))->find();
        if($agentinfo['open_type']==0){
            $users = $Wxopen->where(array('id' => $config['wx_open_id']))->find();
        }else{
            $users = $Wxopen->where(array('id' => $agentinfo['wx_open_id']))->find();
        }
        $options = array(
            'component_token' => $agentinfo['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $agentinfo['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $agentinfo['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $agentinfo['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $agentinfo['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $OpenTemplate= new OpenTemplate();
        $templateid=$OpenTemplate->where(['type'=>'pay_tpl','wx_open_id'=>$config['wx_open_id']])->value('template_id');
        $weObj = new Wxobjopen($options);
        $mas['orderid'] = $orderid;
        $Paylog = new Paylog();
        $Cashier = new MerchantCashier();
        $pay = $Paylog->where($mas)->find();
        $day = strtotime(date('Y-m-d'));
        $tom = strtotime(date('Y-m-d', strtotime('+1 day')));
        $mab['add_time'] = array(array('gt', $day), array('lt', $tom));
        $mab['mid'] = $id;
        $mab['pay_statu'] = 1;
        $sumday = $Paylog->where($mab)->sum('price');       //收款总计
        $wx['pay_fs'] = ['in',[0,2]];
        $wxday = $Paylog->where($mab)->where($wx)->sum('price');       //微信
        $ali['pay_fs'] = ['in',[1,3]];
        $aliday = $Paylog->where($mab)->where($ali)->sum('price');       //支付宝
        $xj['pay_fs'] = ['in',[4]];
        $xjday = $Paylog->where($mab)->where($xj)->sum('price');       //现金
        $card['pay_fs'] = ['in',[8]];
        $cardday = $Paylog->where($mab)->where($card)->sum('price');       //会员卡
        $mi['mid'] = $id;
        $touser = $Cashier->where($mi)->select();
        switch ($pay['pay_fs']) {
            case 0:
                $pay_fs = "微信支付";
                break;
            case 1:
                $pay_fs = "支付宝支付";
                break;
            case 2:
                $pay_fs = "微信刷卡支付";
                break;
            default:
                $pay_fs = "其他方式支付";

        }
        $res=[];
        foreach ($touser as $v) {
            if ($v['is_tz'] == 1) {
                $template = array(
                    'touser' => $v['openid'],
                    'template_id' => $templateid,
//                    'url' => "https://wxpay.weilinzhou.com/admin.php?s=/Authlogin/login/fs/paydetail/payid/" . $pay['id'],
                    'url'=>'',
                    'topcolor' => "#7B68EE",
                    'data' => array(
                        'first' => array('value' => $mach['merchant']."收款提醒", 'color' => "#743A3A"),
                        'keyword1' => array('value' => $pay['price'] . "元", 'color' => '#FF0000'),
                        'keyword2' => array('value' => $pay_fs, 'color' => '#000'),
                        'keyword3' => array('value' =>date("Y-m-d H:i:s", $pay['add_time']) , 'color' => '#000'),
                        'keyword4' => array('value' =>$pay['orderid'] , 'color' => '#000'),
                        'remark' => array('value' =>
                            "---------------------\n" .
                            "微 信  支 付:" . $wxday ."元\n" .
                            "支付宝支付:" .$aliday. "元\n" .
                            "现 金  支 付:" .$xjday. "元\n" .
                            "会员卡支付:" .$cardday. "元\n" .
                            "---------------------\n" .
                            "当日累计收款:" . $sumday . "元\n" .
                            "---------------------",
                            'color' => '#000'),
                    )
                );

                $res[] = $weObj->sendTemplateMessage($template);

            }
        }
        return $res;
    }

    public function sendtemplate($id, $orderid)
    {


    }

    //经营报表  向商家 商家发送
    /*
     * openid  card_id  template_id  keyword1  remark
     *
     * */
    private function pay_count_tomach($data){
        $options = $this->options($data['card_id']);
        $weObj = new Wxobjopen($options);
        $templateid = $data['template_id'];
        $template['touser'] = $data['openid'];
        $template['template_id'] = $templateid;
        $template['url'] = '';
        $template['topcolor'] = "#7B68EE";
        $template['data']['first'] = ['value' => '请查收昨日会员卡运营数据', 'color' => "#000000"];
        $template['data']['keyword1'] = ['value' => $data['keyword1'], 'color' => '#FF0000'];
        $template['data']['keyword2'] = ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000000'];
        $template['data']['remark'] = ['value' => $data['remark'], 'color' => '#000000'];
        //发送
        $res = $weObj->sendTemplateMessage($template);
        if ($res['errcode'] == 0){
            $rarr = $res;
        }else{
            $rarr = $res;
        }
        return $rarr;
    }

    //余额变动  向用户 商家发送
    /*
     * card_id  template_id  type add_balance balance  openid
     * */
    private function balance_change_touser($arr){
        //初始化微信类
        $options = $this->options($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $templateid=$arr['template_id'];
        switch ($arr['type']) {
            case "1":
                $type = "充值";
                break;
            case "2":
                $type = "消费";
                break;
            case "3":
                $type = "同步";
                break;
            default:
                $type = "未知";
                break;
        }
        $add_balance = floor($arr['add_balance']*100)/100;
        $balance = $arr['balance'];
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => trim($templateid),
            'url' => "",
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => '余额' . $type . "提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'keyword2' => ['value' => '余额' . $type, 'color' => '#FF0000'],
                'keyword3' => ['value' => $add_balance.'元', 'color' => '#000'],
                'keyword4' => ['value' => $balance.'元','color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $wxObj->sendTemplateMessage($template);
        $CardUserGet = new CardUserGet();
        $arrp['card_id'] = $arr['card_id'];
        $arrp['code'] = $CardUserGet->where(['openid'=>$arr['openid'],'card_id'=>$arr['card_id']])->value('code');
        $arrp['price'] = $balance;
        $Combalance = new Balance();
        $resu = $Combalance->updatebalance($arrp);
        if ($res['errcode'] == 0){
            $rarr = $resu;
        }else{
            $rarr = $res;
        }
        return $rarr;
    }

    //礼品发放  向用户 由商家发送
    /*
     * openid   template_id  card_id  name   title  rec_id   url first
     * */
    private function gift_put_touser($arr){
//        if ($arr['card_id']){
//            $options = $this->options($arr['card_id']);
//        }else{
            $options = $this->option($arr['mid']);
//        }

        $wxObj = new Wxobjopen($options);
        $Platurl = new Platurl();
        $notify_url = $Platurl->getagenturl('mid',$arr['mid']);
        switch ($arr['type']){
            case "fire":        //激活送券
                $url = $notify_url . $arr['url'];
                $remark = $this->givecards($arr['give_id'],$arr['type']);
                break;
            case "paycard":     //支付送券
                $url = $notify_url . $arr['url'];
                $remark = $this->givecards($arr['give_id'],$arr['type']);
                break;
            case "birthdaycare":     //生日关怀
                $url = $notify_url . $arr['url'];
                $remark = '';
                break;
            case "sharecard":     //分享送券
                $url = $notify_url . $arr['url'];
                $remark = '';
                break;
            case "rankcard":     //等级送券
                $url = $notify_url . $arr['url'];
                $remark = '';
                break;
            case "paymentcard":    //支付后送券送券
                $url = $notify_url . $arr['url'];
                $remark = '';
                break;
            default:
                if ($arr['mid'] == 501){
                    $url = $notify_url . '/mobile.php?s=/cardget/getcards/mid/' . $arr['mid'] . '/rec_id/' . $arr['rec_id'];
                }else{
                    $url = $notify_url . '/mobile.php?s=/cardget/getcards/mid/' . $arr['mid'] . '/rec_id/' . $arr['rec_id'];
                }
                $remark = $this->givecards($arr['rec_id'],$arr['type']);
                break;
        }
        if (!empty($arr['first'])){
            $first = $arr['first'];
        }else{
            $first = '卡券赠送提醒';
        }
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => $arr['template_id'],
            'url' => $url,
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => "$first", 'color' => "#09bb07"],
                'keyword1' => ['value' => $arr['name'], 'color' => '#000'],
                'keyword2' => ['value' => $arr['title'], 'color' => '#FF0000'],
                'keyword3' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'remark' => ['value' => $remark, 'color' => '#000'],
            )
        );

        //发送
        $res = $wxObj->sendTemplateMessage($template);
        if ($res['errcode'] == 0){
            $rarr = $res;
        }else{
            $rarr = $res;
        }
        return $rarr;
    }

    //获取模板ID
    private function get_tpl_id($arr){
        if ($arr['card_id']){
            $mid = $this->get_mid($arr['card_id']);
        }else{
            $mid = $arr['mid'];
        }

        $wx_openid = $this->get_wxopen_id($mid);
        $OpenTemplate= new OpenTemplate();
        $templateid=$OpenTemplate->where(['type'=>$arr['tpl_type'],'wx_open_id'=>$wx_openid])->value('template_id');
        return $templateid;
    }

    //获取模板ID
    private function get_wxopen_id($mid){
        $Merchant = new \app\common\model\Merchant();
        $wx_open_id = $Merchant->where(['id'=>$mid])->value('wx_open_id');
        return $wx_open_id;
    }

    //获取mid
    private function get_mid($card_id){
        $CardMember = new CardMember();
        $mid = $CardMember->where(['card_id'=>$card_id])->value('mid');
        return $mid;
    }

    //配置 初始化
    private function options($card_id){
//        Session::set('openid', null);
        $CardMember = new CardMember();
        $Merchant = new \app\common\model\Merchant();
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $map['id'] = $CardMember->where('card_id',$card_id)->value('mid');
        $merchantinfo=$Merchant->where($map)->field('wx_open_id,agent');
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config =$System->where(array('id' => 1))->find();
        $config =$Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数 根据mid获取
    public function option($mid){

        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $Merchant=new Merchant();
        $merchantinfo=$Merchant->where('id',$mid)->field('wx_open_id,agent')->find();
        $mab['id'] =$merchantinfo['wx_open_id'];
//        $config =$System->where(array('id' => 1))->find();
        $config =$Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //获取规则赠券
    private function givecards($rec_id,$type=''){
        switch ($type){
            case "fire":
                $CardGive = new CardGive();
                $zs_card_all = $CardGive->where(['id' => $rec_id])->value('card_id_list');
                $res = getgivecardnew($zs_card_all, 0);
                break;
            case "paycard":
                $CardPaycard = new CardPaycard();
                $zs_card_all = $CardPaycard->where(['id' => $rec_id])->value('cardlist');
                $res = getpaygive($zs_card_all);
                break;
            default:
                $CardCzLog = new CardCzLog();
                $CardCzgive = new CardCzgive();
                $give_id = $CardCzLog->where(['id' => $rec_id])->value('giveid');
                $zs_card_all = $CardCzgive->where(['id' => $give_id])->value('zs_card_id_all');
                $res = getgivecardnew($zs_card_all, 0);
        }

        return $res;
    }

}